package vip.liux.backend.application.serviceImpl.gen;


import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.TemplateExceptionHandler;
import org.apache.commons.lang3.StringUtils;
import vip.liux.backend.application.service.gen.GenTableDto;
import vip.liux.backend.domain.models.gen.GenTable;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

public class FreeMarkerUtils {
    /**
     * 项目空间路径
     */
    private static final String PROJECT_PATH = "main/java";


    public static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_33);

    static {
        // 这里比较重要，用来指定加载模板所在的路径
        CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreeMarkerUtils.class, "/templates"));
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
        CONFIGURATION.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
        CONFIGURATION.setDateFormat("yyyy-MM-dd");
    }

    public static Map<String, Object> prepareConfiguration(GenTable table) throws IOException {
        String packageName = table.getPackageName();

        Map<String, Object> ctx = new HashMap<>();
        ctx.put("tableName", table.getTableName());
        ctx.put("ClassName", table.getClassName());
        ctx.put("className", StringUtils.uncapitalize(table.getClassName()));
        ctx.put("moduleName", table.getModuleName());
        ctx.put("packageName", packageName);
        ctx.put("datetime", LocalDateTime.now());
        ctx.put("table", table);

        return ctx;
    }

    public static List<String> getTemplateList() {
        List<String> templates = new ArrayList<>();

        // templates.add("java/Entity.ftl");
        // templates.add("java/CreationAuditedEntity.ftl");
        // templates.add("java/AuditedEntity.ftl");

        // templates.add("java/EntityDto.ftl");
        // templates.add("java/CreationAuditedEntityDto.ftl");
        // templates.add("java/AuditedEntityDto.ftl");

        // templates.add("java/Repository.ftl");
        // templates.add("java/JpaRepository.ftl");

        // templates.add("java/CreateDto.ftl");
        // templates.add("java/UpdateDto.ftl");
        // templates.add("java/QueryDto.ftl");
        // templates.add("java/Service.ftl");
        // templates.add("java/AutoMapperProfile.ftl");
        // templates.add("java/ServiceImpl.ftl");
        templates.add("java/Controller.ftl");
        return templates;
    }

    public static String getFileName(String template, GenTableDto genTable) {
        // 文件名称
        String fileName = "";
        // 包路径
        String packageName = genTable.getPackageName();
        // 大写类名
        String className = genTable.getClassName();

        String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");

        if (List.of("java/AuditedAggregateRoot.ftl", "java/AuditedEntity.ftl").contains(template)) {
            fileName = String.format("%s/domain/%s.java", javaPath, className);
        } else if (Objects.equals("java/Repository.ftl", template)) {
            fileName = String.format("%s/domain/%sRepository.java", javaPath, className);
        } else if (Objects.equals("java/JpaRepository.ftl", template)) {
            fileName = String.format("%s/infrastructure/jpa/%sJpaRepository.java", javaPath, className);
        } else if (Objects.equals("java/EntityDto.ftl", template)) {
            fileName = String.format("%s/service/%sDto.java", javaPath, className);
        } else if (Objects.equals("java/CreateDto.ftl", template)) {
            fileName = String.format("%s/service/Create%sDto.java", javaPath, className);
        } else if (Objects.equals("java/UpdateDto.ftl", template)) {
            fileName = String.format("%s/service/Update%sDto.java", javaPath, className);
        } else if (Objects.equals("java/QueryDto.ftl", template)) {
            fileName = String.format("%s/service/Query%sDto.java", javaPath, className);
        } else if (Objects.equals("java/Controller.ftl", template)) {
            fileName = String.format("%s/adapter.controllers/%sController.java", javaPath, className);
        } else if (Objects.equals("java/Service.ftl", template)) {
            fileName = String.format("%s/service/%sService.java", javaPath, className);
        } else if (Objects.equals("java/ServiceImpl.ftl", template)) {
            fileName = String.format("%s/serviceImpl/%sServiceImpl.java", javaPath, className);
        }
        return fileName;
    }

    // public static void main(String[] args) throws IOException, TemplateException {
    //     Configuration cfg = prepareConfiguration();
    //     String className = "User";
    //     String tableName = "user";
    //     String tableComment = "用户";
    //     String packageName = "vip.liux.backend.gen";
    //     String moduleName = "identity";
    //     List<GenTableColumnDto> columns = List.of(
    //             new GenTableColumnDto(1L, "id", "主键",
    //                     GenConst.ColumnType.BIGINT, GenConst.JavaType.Long, "id",
    //                     true, true, true, false, false, false,
    //                     false, GenConst.QueryType.EQUALS, GenConst.HtmlType.INPUT, null, 1),
    //             new GenTableColumnDto(2L, "name", "名称",
    //                     GenConst.ColumnType.VARCHAR, GenConst.JavaType.String, "name",
    //                     false, false, true, true, true, true,
    //                     true, GenConst.QueryType.EQUALS, GenConst.HtmlType.INPUT, null, 2),
    //             new GenTableColumnDto(3L, "age", "年龄",
    //                     GenConst.ColumnType.TIMESTAMP, GenConst.JavaType.Date, "age",
    //                     false, false, false, true, false, true,
    //                     false, GenConst.QueryType.RANGE, GenConst.HtmlType.DATEPICKER, null, 3),
    //             new GenTableColumnDto(5L, "is_active", "是否激活",
    //                     GenConst.ColumnType.BOOLEAN, GenConst.JavaType.Boolean, "isActive",
    //                     false, false, true, false, true, false,
    //                     false, GenConst.QueryType.EQUALS, GenConst.HtmlType.CHECKBOX, null, 5),
    //             new GenTableColumnDto(6L, "price", "价格",
    //                     GenConst.ColumnType.DECIMAL, GenConst.JavaType.BigDecimal, "price",
    //                     false, false, true, true, true, true,
    //                     false, GenConst.QueryType.RANGE, GenConst.HtmlType.INPUT, null, 6),
    //             new GenTableColumnDto(7L, "description", "描述",
    //                     GenConst.ColumnType.VARCHAR, GenConst.JavaType.String, "description",
    //                     false, false, true, true, true, true,
    //                     false, GenConst.QueryType.LIKE, GenConst.HtmlType.TEXTAREA, null, 7)
    //
    //     );
    //
    //     GenTableDto genTableDto = new GenTableDto(1L, tableName, tableComment, className, packageName, moduleName, columns);
    //     FileOutputStream outputStream = new FileOutputStream("output.zip");
    //     ZipOutputStream zip = new ZipOutputStream(outputStream);
    //
    //     for (String templatePath : getTemplateList()) {
    //         Template template = cfg.getTemplate(templatePath);
    //         StringWriter sw = new StringWriter();
    //
    //         template.process(genTableDto, sw);
    //         zip.putNextEntry(new ZipEntry(getFileName(templatePath, genTableDto)));
    //
    //         IOUtils.write(sw.toString(), zip, "UTF-8");
    //         IOUtils.closeQuietly(sw);
    //         zip.flush();
    //         zip.closeEntry();
    //
    //     }
    //     IOUtils.closeQuietly(zip);
    //     // 保存到文件
    // }
}
